package com.tocean.app.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Objects;
import java.util.Optional;
import java.util.function.Supplier;

/**
 * 功能描述：
 * https://mybatis.plus/guide/auto-fill-metainfo.html
 */
@Component
public class AutoFillEntityHandler implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        this.strictInsertFill(metaObject, "createBy", String.class, getAccountId());
        this.strictInsertFill(metaObject, "createAt", () -> LocalDateTime.now(), LocalDateTime.class);
        this.strictInsertFill(metaObject, "updateBy", String.class, getAccountId());
        this.strictInsertFill(metaObject, "updateAt", () -> LocalDateTime.now(), LocalDateTime.class);
        this.strictInsertFill(metaObject, "isDel", Boolean.class, Boolean.FALSE);
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        this.strictUpdateFill(metaObject, "updateBy", String.class, getAccountId());
        this.strictUpdateFill(metaObject, "updateAt", () -> LocalDateTime.now(), LocalDateTime.class);
    }

    private String getAccountId() {
        return "1";
    }

    @Override
    public MetaObjectHandler strictFillStrategy(MetaObject metaObject, String fieldName, Supplier<?> fieldVal) {
        Object obj = fieldVal.get();
        if (Objects.nonNull(obj)) {
            metaObject.setValue(fieldName, obj);
        }

        return this;
    }

}
